﻿using Autodesk.AutoCAD.DatabaseServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace WCAD
{
    public static class XData
    {
        public static void RegApp(string appName)
        {
            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                // 获取注册表表格
                RegAppTable regAppTable = trans.GetObject(db.RegAppTableId, OpenMode.ForWrite) as RegAppTable;

                // 检查是否已经注册了 AppName
                if (!regAppTable.Has(appName))
                {
                    // 创建一个新的注册表记录
                    RegAppTableRecord regAppRecord = new RegAppTableRecord();
                    regAppRecord.Name = appName;

                    // 将注册表记录添加到注册表表格
                    regAppTable.Add(regAppRecord);
                    trans.AddNewlyCreatedDBObject(regAppRecord, true);
                }
                // 提交事务
                trans.Commit();
            }
        }
        public static void SetXData(Entity entity, string appName,List<string> datas)
        {
            ResultBuffer rb = new ResultBuffer();
            rb.Add(new TypedValue((int)DxfCode.ExtendedDataRegAppName, appName));
            foreach (var data in datas)
            {
                rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, data));
            }
            entity.XData = rb;
        }
        public static void SetXData(Entity entity, string appName, string data)
        {
            SetXData(entity, appName, new List<string>() { data });
        }
        public static TypedValue[] GetXData(this Entity entity, string appName)
        {
            ResultBuffer rb = entity.GetXDataForApplication(appName);
            if (rb != null)
            {
                TypedValue[] values = rb.AsArray();
                return values;
            }
            return null;
        }
    }
}
